package com.bks.service;

import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.ejb.TransactionManagement;
import javax.ejb.TransactionManagementType;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;

@Path("/crud")
@Produces(MediaType.APPLICATION_JSON)
@Stateless
@TransactionManagement(TransactionManagementType.CONTAINER)
public class CrudService {

	@PersistenceContext(unitName="bks")
	private EntityManager em;

	@GET
	@Path("{entityName}")
	public Object list(@PathParam("entityName") String entityName){
		System.out.println(entityName);
		Query query = this.em.createNamedQuery(entityName + ".findAll");
		return query.getResultList();
	}

	@POST
	@Path("{entityName}")
	@TransactionAttribute(TransactionAttributeType.REQUIRED)
	public Object post(@PathParam("entityName") String entityName, String object) throws JsonSyntaxException, ClassNotFoundException{
		Gson gson = new Gson();

		Object entity = gson.fromJson(object, Class.forName("com.bks.model." + entityName));

		//		this.em.getTransaction().begin();
		this.em.persist(entity);
		//		this.em.getTransaction();

		return entity;
	}

}
